package com.dongjiantong.farmrecords.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.biz.enums.EarMarkType;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.model.EarMarkLife;
import com.dongjiantong.biz.service.EarMarkLifeWriteService;
import com.dongjiantong.biz.service.EarMarksWriteService;
import com.dongjiantong.common.exceptions.HttpCode;
import com.dongjiantong.common.exceptions.OPServerException;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.farmrecords.dto.RetailRecordsImmunizationDto;
import com.dongjiantong.farmrecords.enums.FarmRecordsNumberStatus;
import com.dongjiantong.farmrecords.mapper.FarmRecordsRetailImmunizationMapper;
import com.dongjiantong.farmrecords.mapper.FarmRecordsRetailImmunizationSubMapper;
import com.dongjiantong.farmrecords.model.FarmRecordsRetailImmunization;
import com.dongjiantong.farmrecords.model.FarmRecordsRetailImmunizationSub;
import com.dongjiantong.farmrecords.service.FarmRecordsRetailImmunizationService;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.user.enums.FarmsEnum;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author Lee
 * @date 2018/1/14
 */
@Slf4j
@Service(version = "1.0.0")
public class FarmRecordsRetailImmunizationServiceImpl extends ServiceMybatis<FarmRecordsRetailImmunization> implements FarmRecordsRetailImmunizationService {
    @Resource
    private FarmRecordsRetailImmunizationMapper farmrecordsRetailImmunizationMapper;
    @Resource
    private FarmRecordsRetailImmunizationSubMapper farmRecordsRetailImmunizationSubMapper;

    @Reference(version = "1.0.0")
    private EarMarksWriteService earMarksWriteService;
    @Reference(version = "1.0.0")
    private EarMarkLifeWriteService earMarkLifeWriteService;

    @Override
    public PageInfo<FarmRecordsRetailImmunization> selectListByStatus(Integer pageNum, Integer pageSize, Integer status, Long farmId) {
        PageHelper.startPage(pageNum,pageSize);

        Map<String,Object> map = Maps.newHashMap();

        if (status != null) {
            map.put("status",status);
        }

        map.put("farm_id",farmId);
        map.put("delete_flag",FarmRecordsNumberStatus.EFFECTIVE.getCode());

        List<FarmRecordsRetailImmunization> farmRecordsRetailImmunizationList = farmrecordsRetailImmunizationMapper.selectListByStatus(map);
        return new PageInfo<FarmRecordsRetailImmunization>(farmRecordsRetailImmunizationList);
    }

    @Override
    public PageInfo<FarmRecordsRetailImmunization> selectByMap(Integer pageNum, Integer pageSize, Map map) {
        if (farmrecordsRetailImmunizationMapper == null){
            throw new OPServerException("farmrecordsRetailImmunizationMapper 为null,请检查");
        }

        try {
            PageHelper.startPage(pageNum,pageSize);
            //查询有效单据
            map.put("delete_flag", FarmRecordsNumberStatus.EFFECTIVE.getCode());
            //查询已启用的养殖场
            map.put("farmStatus", FarmsEnum.status_true.getCode());
            List<FarmRecordsRetailImmunization> list = farmrecordsRetailImmunizationMapper.selectByMapApp(map);

            return new PageInfo<FarmRecordsRetailImmunization>(list);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @Override
    public RetailRecordsImmunizationDto selectById(Long id) {
        if (farmrecordsRetailImmunizationMapper == null){
            throw new OPServerException("farmrecordsRetailImmunizationMapper 为null,请检查");
        }

        try {
            FarmRecordsRetailImmunization farmRecordsRetailImmunization = farmrecordsRetailImmunizationMapper.selectById(id);
            RetailRecordsImmunizationDto retailRecordsImmunizationDto = null;
            if (farmRecordsRetailImmunization != null) {
                retailRecordsImmunizationDto =  new RetailRecordsImmunizationDto();
                List<FarmRecordsRetailImmunizationSub> farmRecordsRetailImmunizationSubList = farmRecordsRetailImmunizationSubMapper.selectByVaccineId(farmRecordsRetailImmunization.getId());

                retailRecordsImmunizationDto.setImmunizationRecord(farmRecordsRetailImmunization);
                retailRecordsImmunizationDto.setVaccines(farmRecordsRetailImmunizationSubList);

                if (!Strings.isNullOrEmpty(farmRecordsRetailImmunization.getEar_number_json())) {
                    retailRecordsImmunizationDto.setOriginal_ear(farmRecordsRetailImmunization.getEar_number());
                }
            }
            return retailRecordsImmunizationDto;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.INTERNAL_SERVER_ERROR,HttpCode.INTERNAL_SERVER_ERROR.getMessage());
        }
    }

    @Override
    public Map<String, Object> createOne(LoginInfo loginInfo, RetailRecordsImmunizationDto retailRecordsImmunizationDto, Integer toStatus) {
        if (farmrecordsRetailImmunizationMapper == null){
            throw new OPServerException("farmrecordsRetailImmunizationMapper 为null,请检查");
        }
        if (farmRecordsRetailImmunizationSubMapper == null){
            throw new OPServerException("farmRecordsRetailImmunizationSubMapper 为null,请检查");
        }

        FarmRecordsRetailImmunization farmRecordsRetailImmunization = retailRecordsImmunizationDto.getImmunizationRecord();
        List<FarmRecordsRetailImmunizationSub> farmRecordsRetailImmunizationSubList = retailRecordsImmunizationDto.getVaccines();

        Integer fromStatus = farmRecordsRetailImmunization.getStatus();

        //todo 生成单据号
        //单据生成规则暂未定(此处为测试)
        String prefix = "RMY";
        prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());
        String number = ReportNumberMakerUtil.create(prefix,farmrecordsRetailImmunizationMapper.findMaxNumber(prefix));
        farmRecordsRetailImmunization.setNumber(number);

        farmRecordsRetailImmunization.setProvince_id(loginInfo.getProvinceId());
        farmRecordsRetailImmunization.setCity_id(loginInfo.getCityId());
        farmRecordsRetailImmunization.setRegion_id(loginInfo.getRegionId());
        farmRecordsRetailImmunization.setStreet_id(loginInfo.getStreetId());
        farmRecordsRetailImmunization.setVillage_id(loginInfo.getVillageId());

        farmRecordsRetailImmunization.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());

        //首免的子表信息
        if (farmRecordsRetailImmunizationSubList.get(0) == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,"对象为空");
        }
        FarmRecordsRetailImmunizationSub farmRecordsRetailImmunizationSub = farmRecordsRetailImmunizationSubList.get(0);

        if (fromStatus == 0 && toStatus == null) {
            //直接暂存

            //todo 新建免疫记录主体表信息
            farmrecordsRetailImmunizationMapper.createOne(farmRecordsRetailImmunization);


            //todo 免疫记录首免信息 (既 免疫记录子表信息)
            if (farmRecordsRetailImmunization.getId() != null && farmRecordsRetailImmunization.getId() != 0) {
                farmRecordsRetailImmunizationSub.setVaccine_id(farmRecordsRetailImmunization.getId());
                farmRecordsRetailImmunizationSub.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());
                farmRecordsRetailImmunizationSubMapper.createOne(farmRecordsRetailImmunizationSub);
            }

        }else if (!fromStatus.equals(toStatus) && FarmRecordsNumberStatus.SUBMIT.getCode().equals(toStatus)) {
            //直接提交

            //todo 新建免疫记录主体表信息
            farmRecordsRetailImmunization.setStatus(toStatus);
            farmrecordsRetailImmunizationMapper.createOne(farmRecordsRetailImmunization);

            //todo 免疫记录首免信息 (既 免疫记录子表信息)
            if (farmRecordsRetailImmunization.getId() != null && farmRecordsRetailImmunization.getId() != 0) {
                farmRecordsRetailImmunizationSub.setVaccine_id(farmRecordsRetailImmunization.getId());
                farmRecordsRetailImmunizationSub.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());
                farmRecordsRetailImmunizationSubMapper.createOne(farmRecordsRetailImmunizationSub);
            }

            //todo 备份首免操作的耳标
            if (!Strings.isNullOrEmpty(farmRecordsRetailImmunization.getEar_number_json())) {
                //更新耳标的状态
                List<String> earNumberList = farmRecordsRetailImmunization.getEar_number();

                Map<String,Object> earParam = Maps.newHashMap();
                earParam.put("markNumbers",earNumberList);
                earParam.put("status", EarMarkType.status_wear.getCode());
                earParam.put("woreAt",new Date());

                earMarksWriteService.updateMarks(earParam);

                //新增耳标的使用记录
                List<EarMarkLife> earMarkLiveList = Lists.newArrayList();
                for (String earNumber : earNumberList) {
                    if (!Strings.isNullOrEmpty(earNumber)) {
                        EarMarkLife earMarkLife = new EarMarkLife();
                        earMarkLife.setMark_number(earNumber);
                        earMarkLife.setMark_type(farmRecordsRetailImmunization.getBreed_second_type());
                        earMarkLife.setReport_id(farmRecordsRetailImmunization.getId());
                        earMarkLife.setReport_name(farmRecordsRetailImmunization.getNumber());
                        earMarkLife.setReport_type(ReportType.IMMUNIZATION_RECORD_MANAGER.value());
                        earMarkLife.setIs_selected(1);
                        earMarkLife.setOperator_id(loginInfo.getId());
                        earMarkLife.setOperator_name(loginInfo.getRealName());
                        earMarkLife.setCreated_at(new Date());
                        earMarkLiveList.add(earMarkLife);
                    }
                }

                earMarkLifeWriteService.insertList(earMarkLiveList);
            }
        }

        //todo 生成日志记录

        Map<String,Object> result = Maps.newHashMap();
        if (farmRecordsRetailImmunization.getId() != null && farmRecordsRetailImmunization.getId() != 0) {
            result.put("receiptId", farmRecordsRetailImmunization.getId());
        }
        if (farmRecordsRetailImmunizationSub.getId() != null && farmRecordsRetailImmunizationSub.getId() != 0) {
            result.put("subId", farmRecordsRetailImmunizationSub.getId());
        }

        return result;
    }

    @Override
    public Integer updateByIdOrNumber(LoginInfo loginInfo, RetailRecordsImmunizationDto retailRecordsImmunizationDto, Integer toStatus) {
        if (farmrecordsRetailImmunizationMapper == null){
            throw new OPServerException("farmrecordsRetailImmunizationMapper 为null,请检查");
        }

        try {
            FarmRecordsRetailImmunization farmRecordsRetailImmunization = retailRecordsImmunizationDto.getImmunizationRecord();
            List<FarmRecordsRetailImmunizationSub> farmRecordsRetailImmunizationSubList = retailRecordsImmunizationDto.getVaccines();
            List<String> original_ear_list = retailRecordsImmunizationDto.getOriginal_ear();

            if (toStatus != null) {
                farmRecordsRetailImmunization.setStatus(toStatus);
            }
            farmRecordsRetailImmunization.setUpdated_at(new Date());
            //todo 更新主表中的数据
            Integer con = farmrecordsRetailImmunizationMapper.updateByPrimaryKeySelective(farmRecordsRetailImmunization);

            if (farmRecordsRetailImmunizationSubList.size() == 1) {
                for (FarmRecordsRetailImmunizationSub farmRecordsRetailImmunizationSub : farmRecordsRetailImmunizationSubList) {
                    //todo 更新子表数据
                    farmRecordsRetailImmunizationSubMapper.updateByPrimaryKeySelective(farmRecordsRetailImmunizationSub);
                }
            } else if (farmRecordsRetailImmunizationSubList.size() > 1) {
                //新增免疫子表信息
                FarmRecordsRetailImmunizationSub farmRecordsRetailImmunizationSub = farmRecordsRetailImmunizationSubList.get(farmRecordsRetailImmunizationSubList.size() - 1);
                farmRecordsRetailImmunizationSub.setDelete_flag(FarmRecordsNumberStatus.EFFECTIVE.getCode());
                farmRecordsRetailImmunizationSubMapper.createOne(farmRecordsRetailImmunizationSub);
            }

            //更新耳标数据
            this.updateEarNumber(loginInfo,farmRecordsRetailImmunization,original_ear_list);

            return con;
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
            throw new OPServerException(HttpCode.DATA_UPDATE_FAIL,HttpCode.DATA_UPDATE_FAIL.getMessage());
        }
    }

    @Override
    public Boolean updateEarNumber(LoginInfo loginInfo, FarmRecordsRetailImmunization farmRecordsRetailImmunization, List<String> original_ear_list) {

        if (farmRecordsRetailImmunization == null) {
            throw new OPServerException(HttpCode.BAD_REQUEST,HttpCode.BAD_REQUEST.getMessage());
        }

        List<String> earNumberList = farmRecordsRetailImmunization.getEar_number();
        boolean result = false;
        boolean after = false;
        boolean before = false;

        if (earNumberList != null) {
            //比对两组耳标
            if (earNumberList.size() > 0) {
                if (original_ear_list.size() > 0) {
                    Collection collection = Lists.newArrayList(earNumberList);
                    collection.retainAll(original_ear_list);

                    //取出earNumberList 里新增的耳标
                    earNumberList.removeAll(collection);

                    //取出original_ear_list 里需要 更改成 未使用状态的耳标
                    original_ear_list.removeAll(collection);
                }
            }

            //对新增耳标操作
            if (earNumberList.size() > 0) {
                //修改耳标为配标状态
                //更新耳标的状态
                Map<String,Object> earParam = Maps.newHashMap();
                earParam.put("markNumbers",earNumberList);
                earParam.put("status", EarMarkType.status_wear.getCode());
                earParam.put("woreAt",new Date());

                after = earMarksWriteService.updateMarks(earParam);

                //新增耳标的使用记录
                List<EarMarkLife> earMarkLiveList = Lists.newArrayList();
                for (String earNumber : earNumberList) {
                    EarMarkLife earMarkLife = new EarMarkLife();
                    earMarkLife.setMark_number(earNumber);
                    earMarkLife.setMark_type(farmRecordsRetailImmunization.getBreed_second_type());
                    earMarkLife.setReport_id(farmRecordsRetailImmunization.getId());
                    earMarkLife.setReport_name(farmRecordsRetailImmunization.getNumber());
                    earMarkLife.setReport_type(ReportType.IMMUNIZATION_RECORD_MANAGER.value());
                    earMarkLife.setIs_selected(1);
                    earMarkLife.setOperator_id(loginInfo.getId());
                    earMarkLife.setOperator_name(loginInfo.getRealName());
                    earMarkLife.setCreated_at(new Date());
                    earMarkLiveList.add(earMarkLife);
                }

                earMarkLifeWriteService.insertList(earMarkLiveList);

            }

            //对原有需要更新为未使用状态的耳标操作
            if (original_ear_list.size() > 0) {
                //更新耳标使用状态为入库状态
                //更新耳标的状态
                Map<String,Object> earParam = Maps.newHashMap();
                earParam.put("markNumbers",original_ear_list);
                earParam.put("status", EarMarkType.status_put.getCode());
                earParam.put("createdAt",new Date());

                before = earMarksWriteService.updateMarks(earParam);

            }
        }

        if (after && before) {
            result = true;
        }
        return result;
    }
}
